import React, { useEffect, useState } from 'react';
import { Card, Row, Col, Spin, message, Button, Popconfirm, Input } from 'antd';
import axios from 'axios';

const { Search } = Input;

interface Prize {
  id: number;
  prize_name: string;
  prize_description: string;
  prize_image: string;
  points: number;
  stock: number;
}

const PrizeList: React.FC = () => {
  const [prizes, setPrizes] = useState<Prize[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [deletingId, setDeletingId] = useState<number | null>(null);
  const [searchText, setSearchText] = useState<string>('');

  useEffect(() => {
    fetchPrizes();
  }, []);

  const fetchPrizes = async () => {
    setLoading(true);
    try {
      const res = await axios.get('http://localhost:5000/api/getAllPrizes');
      setPrizes(res.data);
    } catch (error: any) {
      message.error('获取奖品失败: ' + (error?.response?.data?.message || error.message));
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id: number) => {
    setDeletingId(id);
    try {
      await axios.delete(`http://localhost:5000/api/delPrize/${id}`);
      message.success('删除成功');
      fetchPrizes();
    } catch (error: any) {
      message.error('删除失败: ' + (error?.response?.data?.message || error.message));
    } finally {
      setDeletingId(null);
    }
  };

  // 过滤后的奖品列表
  const filteredPrizes = prizes.filter((prize) =>
    prize.prize_name.toLowerCase().includes(searchText.toLowerCase())
  );

  return (
    <div style={{ padding: '40px' }}>
      <h2 style={{ textAlign: 'center', marginBottom: 24 }}>奖品列表</h2>

      {/* 搜索框 */}
      <div style={{ textAlign: 'center', marginBottom: 40 }}>
        <Input
          placeholder="搜索奖品名称"
          allowClear
          size="large"
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          style={{ maxWidth: 400, width: '100%' }}
        />
      </div>

      {loading ? (
        <Spin size="large" style={{ display: 'block', margin: '100px auto' }} />
      ) : (
        <Row gutter={[24, 24]}>
          {filteredPrizes.length > 0 ? (
            filteredPrizes.map((prize) => (
             <Col xs={24} sm={12} md={8} lg={6} key={prize.id}>
  <Card
    hoverable
    style={{ height: '100%' }} // 保持卡片高度一致
    cover={
      <div style={{ height: 200, overflow: 'hidden' }}>
        <img
          src={`http://localhost:5000${prize.prize_image}`}
          alt={prize.prize_name}
          style={{ width: '100%', height: '100%', objectFit: 'cover' }}
        />
      </div>
    }
  >
    {/* 使用 flex 容器分配内容区域 */}
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ flex: '1 1 auto' }}>
        <Card.Meta
          title={prize.prize_name}
          description={
            <>
              <p style={{ marginBottom: 4 }}>{prize.prize_description || '暂无描述'}</p>
              <p style={{ margin: 0 }}>🎁 积分: {prize.points}</p>
              <p style={{ margin: 0 }}>📦 库存: {prize.stock}</p>
            </>
          }
        />
      </div>

      <div style={{ marginTop: 'auto', display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
  <Button
    type="default"
    size="small"
    onClick={() => window.location.href = `/EditPrizes/${prize.id}`}
  >
    修改
  </Button>

  <Popconfirm
    title="确认删除该奖品吗？"
    onConfirm={() => handleDelete(prize.id)}
    okText="删除"
    cancelText="取消"
  >
    <Button
      type="primary"
      danger
      loading={deletingId === prize.id}
      size="small"
    >
      删除
    </Button>
  </Popconfirm>
</div>


    </div>
  </Card>
</Col>

            ))
          ) : (
            <p style={{ textAlign: 'center', width: '100%' }}>未找到匹配的奖品</p>
          )}
        </Row>
      )}
    </div>
  );
};

export default PrizeList;
